<template>
  <div class="app-container">
    <el-form :model="queryParams"
             ref="queryForm"
             :inline="true"
             v-show="showSearch"
             label-width="68px"
    >
      <el-form-item label="用户名称"
                    prop="name"
      >
        <el-input v-model="queryParams.name"
                  placeholder="请输入用户名称"
                  clearable
                  size="small"
                  @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号码"
                    prop="phone"
      >
        <el-input v-model="queryParams.phone"
                  placeholder="请输入用户手机号码"
                  clearable
                  size="small"
                  @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户地址"
                    prop="addr"
      >
        <el-input v-model="queryParams.addr"
                  placeholder="请输入用户地址"
                  clearable
                  size="small"
                  @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态"
                    prop="status"
      >
        <el-select v-model="queryParams.status"
                   placeholder="用户状态"
                   size="small"
                   clearable
                   @keyup.enter.native="handleQuery"
        >
          <!-- <el-option
                v-for="dict in statusOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              /> -->
          <el-option label="启用"
                     value="1"
          ></el-option>
          <el-option label="禁用"
                     value="0"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary"
                   icon="el-icon-search"
                   size="mini"
                   @click="handleQuery"
        >搜索
        </el-button>
        <el-button icon="el-icon-refresh"
                   size="mini"
                   @click="resetQuery"
        >重置
        </el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10"
            class="mb8"
    >
      <el-col :span="1.5">
        <el-button type="primary"
                   plain
                   icon="el-icon-plus"
                   size="mini"
                   @click="handleAdd"
                   v-hasPermi="['system:appsecret:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success"
                   plain
                   icon="el-icon-edit"
                   size="mini"
                   :disabled="single"
                   @click="handleUpdate"
                   v-hasPermi="['system:appsecret:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger"
                   plain
                   icon="el-icon-delete"
                   size="mini"
                   :disabled="multiple"
                   @click="handleDelete"
                   v-hasPermi="['system:appsecret:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning"
                   plain
                   icon="el-icon-download"
                   size="mini"
                   @click="handleExport"
                   v-hasPermi="['system:appsecret:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch"
                     @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table v-loading="loading"
              :data="appsecretList"
              @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection"
                       width="55"
                       align="center"
      />
      <el-table-column label="用户地址"
                       align="center"
                       prop="id"
                       v-if="false"
      />
      <el-table-column label="用户名称"
                       align="center"
                       prop="name"
      />
      <el-table-column label="appid"
                       align="center"
                       prop="appid"
      />
      <el-table-column label="密码"
                       align="center"
                       prop="secret"
      >
        <template slot-scope="scope">
          <el-input class="passwordType" show-password v-model="scope.row.secret"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="设备ID"
                       align="center"
                       prop="deviceId"
      />
      <el-table-column label="总调用次数"
                       align="center"
                       prop="totalCount"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.totalCount">{{ scope.row.totalCount }}</span>
          <span v-else>无</span>
        </template>
      </el-table-column>
      <el-table-column label="已调用次数"
                       align="center"
                       prop="transferCount"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.transferCount">{{ scope.row.transferCount }}</span>
          <span v-else>无</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="ip百名单" align="center" prop="ips"/> -->
      <el-table-column label="手机号码"
                       align="center"
                       prop="phone"
      />
      <el-table-column label="状态"
                       align="center"
                       key="status"
      >
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status"
                     :active-value="1"
                     :inactive-value="0"
                     @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <!-- <el-table-column label="用户地址" align="center" prop="addr"/> -->
      <el-table-column label="操作"
                       align="center"
                       class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button size="mini"
                     type="text"
                     icon="el-icon-edit"
                     @click="handleUpdate(scope.row)"
                     v-hasPermi="['system:appsecret:edit']"
          >修改
          </el-button>
          <el-button size="mini"
                     type="text"
                     icon="el-icon-delete"
                     @click="handleDelete(scope.row)"
                     v-hasPermi="['system:appsecret:remove']"
          >删除
          </el-button>
          <el-button size="mini"
                     type="text"
                     icon="el-icon-zoom-in"
                     @click="handleWatch(scope.row)"
                     v-hasPermi="['system:info:remove']"
          >查看
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0"
                :total="total"
                :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize"
                @pagination="getList"
    />

    <!-- 添加或修改【请填写功能名称】对话框 -->
    <el-dialog :title="title"
               :visible.sync="open"
               width="500px"
               append-to-body
    >
      <el-form ref="form"
               :model="form"
               :rules="rules"
               label-width="80px"
      >
        <el-form-item label="用户名称"
                      prop="name"
        >
          <el-input v-model="form.name"
                    placeholder="请输入用户名称"
          />
        </el-form-item>

        <el-form-item label="智能门锁"
                      prop="floor"
        >
          <el-select v-model="form.floor" multiple placeholder="请选择" filterable style="width: 100%" @change="$forceUpdate()">
            <el-option
              v-for="item in DoorLock"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="智能电表"
                      prop="electric"
        >
          <el-select v-model="form.electric" multiple placeholder="请选择" filterable style="width: 100%" @change="$forceUpdate()">
            <el-option
              v-for="item in eleMater"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="智能水表"
                      prop="water"
        >
          <el-select v-model="form.inteWater" placeholder="请选择" multiple filterable style="width: 100%" @change="$forceUpdate()">
            <el-option
              v-for="item in waterMater"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>

        </el-form-item>
        <el-form-item label="调用次数"
                      prop="totalCount"
        >
          <el-input v-model="form.totalCount"
                    placeholder="请输入总调用次数"
          />
        </el-form-item>
        <!--     <el-form-item label="已调用次数" prop="transferCount">
          <el-input v-model="form.transferCount" placeholder="请输入已调用次数"/>
        </el-form-item> -->
        <el-form-item label="ip白名单"
                      prop="ips"
        >
          <el-input v-model="form.ips"
                    type="textarea"
                    placeholder="*代表全部"
          />
        </el-form-item>
        <el-form-item label="手机号码"
                      prop="phone"
        >
          <el-input v-model="form.phone"
                    placeholder="请输入用户手机号码"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio v-model="radio"
                      :label="0"
            >禁用
            </el-radio>
            <el-radio v-model="radio"
                      :label="1"
            >启用
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="用户地址"
                      prop="addr"
        >
          <el-input v-model="form.addr"
                    placeholder="请输入用户地址"
          />
        </el-form-item>
      </el-form>
      <div slot="footer"
           class="dialog-footer"
      >
        <el-button type="primary"
                   @click="submitForm"
        >确 定
        </el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看表单 -->
    <el-dialog :title="title"
               :visible.sync="openView"
               width="700px"
               append-to-body
    >
      <el-form
        ref="form"
        :model="form"
        label-width="120px"
        size="mini"
        align-item="left"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="姓名">{{ form.name }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="appId">{{ form.appid }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="密钥">{{ form.secret }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备ID">{{ form.deviceId }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="总调用次数">{{ form.totalCount }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="已调用次数">{{ form.transferCount }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号码">{{ form.phone }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">{{ form.status }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="地址">{{ form.addr }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="ip白名单">{{ form.ips }}</el-form-item>
          </el-col>

        </el-row>
      </el-form>
      <div slot="footer"
           class="dialog-footer"
      >
        <el-button @click="openView = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listAppsecret,
  getAppsecret,
  delAppsecret,
  addAppsecret,
  updateAppsecret,
  exportAppsecret,
  changeUserStatus,
  getDevies
} from '@/api/lock/sysAppsecret'
import { getDevices } from '@/api/brand/brand'
import log from '../monitor/job/log'

export default {
  name: 'Appsecret',
  components: {},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      appsecretList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      openView: false,
      // radio
      radio: undefined,
      // passwordType
      passwordType: 'password',
      // 状态数据字典
      statusOptions: [],
      DoorLock: [],//门锁
      eleMater: [],//电表
      waterMater: [],//水表
      deviceId: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        appid: undefined,
        secret: undefined,
        totalCount: undefined,
        transferCount: undefined,
        ips: undefined,
        phone: undefined,
        addr: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        phone: [
          { required: true, message: '手机号码不能为空', trigger: 'blur' },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur'
          }
        ],
        name: [
          { required: true, message: '请输入用户名称', trigger: 'blur' }
        ],
        deviceId: [
          { required: true, message: '请输入设备ID', trigger: 'blur' },
          {
            pattern: /^\d{6,10}$/,
            message: '请输入6-10数字设备ID',
            trigger: 'blur'
          }
        ],
        floor: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        electric: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        // water:[
        //   {required: true, message: '请选择', trigger: 'change'}
        // ],
        status: [
          { required: true, message: '请选择状态', trigger: 'blur' }
        ],
        addr: [
          { required: true, message: '请输入地址', trigger: 'blur' }
        ],
        ips: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        totalCount: [
          { required: true, message: '请输入', trigger: 'blur' },
          {
            pattern: /^[0-9]+$/,
            message: '请输入数字',
            trigger: 'blur'
          }
        ]
      },
      icon2: 'el-icon-warning-outline',
      icon1: 'el-icon-view'
    }
  },
  created() {
    this.getList()
    this.getDevices()
    this.getDicts('sys_normal_disable').then(response => {
      this.statusOptions = response.data
      // console.log('123', this.statusOptions)
      // this.statusOptions.forEach(item => {
      //   item.dictValue = parseInt(item.dictValue)
      //   console.log(item.dictValue)
      // });
    })
  },
  methods: {
    /** 查询【请填写功能名称】列表 */
    getList() {
      this.loading = true
      listAppsecret(this.queryParams).then(response => {
        this.appsecretList = response.rows
        console.log(this.appsecretList)
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        appid: undefined,
        secret: undefined,
        totalCount: undefined,
        transferCount: undefined,
        ips: undefined,
        phone: undefined,
        addr: undefined,
        createTime: undefined,
        createBy: undefined,
        updateTime: undefined,
        updateBy: undefined,
        status: '0'
      }
      this.resetForm('form')
    },
    //获取设备列表
    getDevices() {
      getDevices().then(res => {
        if (res.code == 200) {
          console.log(res)
        }
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加【用户信息】'
      getDevices().then((response) => {
        this.deviceId = response.data
        this.DoorLock = response.data[0].children
        this.eleMater = response.data[1].children
        this.waterMater = response.data[2].children
        console.log(this.form)
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getDevices().then((response) => {
        this.deviceId = response.data
        this.DoorLock = response.data[0].children
        this.eleMater = response.data[1].children
        this.waterMater = response.data[2].children
      })
      getAppsecret(id).then(response => {
        this.open = true
        this.title = '修改【用户信息】'
        this.form = response.data
        this.DoorLock=[]
        this.eleMater=[]
        this.waterMater=[]
        response.data.deviceId.split(',').forEach(item => {
          if (item.indexOf('Voltmeter') != -1) {
            this.eleMater.push(item)
          } else if (item.indexOf('Water') != -1) {
            this.waterMater.push(item)
          } else if (item.indexOf('lock') != -1){
            this.DoorLock.push(item)
          }
          this.form.floor=this.DoorLock
          this.form.electric=this.eleMater
          this.form.inteWater=this.waterMater
        })
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            let arr = []
            arr[0] = this.form.floor
            arr[1] = this.form.electric
            arr[2] = this.form.inteWater
            this.form.deviceId = String(arr.join(',').substr(0, arr.join(',').length - 1))
            updateAppsecret(this.form).then(response => {
              this.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            let arr = []
            arr[0] = this.form.floor
            arr[1] = this.form.electric
            arr[2] = this.form.inteWater
            this.form.deviceId = String(arr.join(',').substr(0, arr.join(',').length - 1))
            addAppsecret(this.form).then(response => {
              this.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$confirm('是否确认删除 编号为"' + ids + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delAppsecret(ids)
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams
      this.$confirm('是否确认导出所有 数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return exportAppsecret(queryParams)
      }).then(response => {
        this.download(response.msg)
      })
    },
    // 用户状态修改
    handleStatusChange(row) {

      changeUserStatus(row.id, row.status).then(response => {
        this.$message({
          message: '操作成功',
          type: 'warning'
        })
      })

    },
    //查看按钮
    handleWatch(row) {
      getAppsecret(row.id).then(response => {
        this.form = response.data
        this.openView = true
        this.title = '锁信息'
      })
    }

  }
}
</script>
